import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Affix, Button, Form, message, InputNumber } from 'antd';
import { messages } from 'share/common';
import 'styles/expense-reimbursement-control/mileage-subsidy/new-mileage-subsidy.scss';
import Priority from 'components/template/priority';
import { formData } from 'containers/expense-reimbursement-control/new-mileage-subsidy/dataSources';
import mileageService from '../mileage-service';
import { permission } from 'containers/finance-setting/permisson';

@connect(mapStateToProps)
@permission
class NewLadderModeRule extends Component {

  static propTypes = {};

  state = {
    formList: {
      'enabled': { initData: true, valuePropName: 'checked' },
      'userGroupVOs': { initData: { applicationUserGroupScope: 1001 } },
      'name': {},
      'currency': {},
    }, // 表单项
    submitLoading: false,
    priority: {}
  };


  componentWillMount() {
    this.handleInit();
  }

  handleInit = () => {
    // 初始化
    const { formList } = this.state;
    const { params, params: { levelCode, levelOrgId, levelOrgName, companies, companyNameList, stepRuleId, stepVOs, applicationUserGroupScope, optionalUserGroup } } = this.props;
    let { priority } = this.state;
    stepVOs.forEach((item, index) => {
      formList[`stepVOs${index}`] = {};
      formList[`stepVOs${index}`].name = `${item.startUnit}~${item.endUnit === '-1' ? messages('expense-12.key146')/*无限*/ : item.endUnit}`;
      formList[`stepVOs${index}`].initData = item.unitPrice;
    });
    this.setState({ formList });
    if (!stepRuleId) {
      return;
    }
    Object.keys(formList)
      .map(item => {
        if (params[item] !== null && params[item] !== void 0) {
          formList[item].initData = params[item];
        }
      });
    formList.userGroupVOs.initData = { applicationUserGroupScope, optionalUserGroup };
    priority.distribution = {};
    companies && (priority.distribution.companies = companies.map((item, index) => {
      return {
        name: companyNameList[index],
        id: item
      };
    }));
    priority = { ...priority, levelCode, levelOrgId, levelOrgName };
    this.setState({ priority, formList });
  };

  handlePriority = (priority) => {
    this.setState({ priority });
  };

  handleSubmit = e => {
    e.preventDefault();
    const { priority } = this.state;
    this.props.form.validateFields((err, values) => {
      if (!err) {
        if(priority && (priority.levelCode === 'SET_OF_BOOK') && priority.distribution && priority.distribution.companies &&
          !priority.distribution.companies.length) {
          message.error(messages('expense-12.key150')/*请选择启用公司*/);
          return;
        }
        if(values.userGroupVOs && values.userGroupVOs.applicationUserGroupScope === 1002 &&
          (!values.userGroupVOs.optionalUserGroup || !values.userGroupVOs.optionalUserGroup.length)) {
          message.error(messages('expense-12.key151')/*请选择适用人员*/);
          return;
        }

        const { params: { stepMileageOptId, stepVOs, stepRuleId } } = this.props;
        let count = 0;
        Object.keys(values)
          .forEach(item => {
            if (/stepVOs\d/.test(item)) {
              stepVOs[count].unitPrice = values[item];
              count++;
            }
          });
        values = { ...values, ...values.userGroupVOs, stepVOs };
        delete values.userGroupVOs;
        this.setState({ submitLoading: true });
        mileageService.addLadderModeRule({ ...values, stepMileageOptId, stepRuleId })
          .then(() => {
            message.success(messages('common.save.success',{arg1: ''})/*{arg1} 保存成功*/);
            this.props.close('modeRule');
          })
          .finally(() => {
            this.setState({ submitLoading: false });
          });
      }
    });
  };

  handleCancel = () => {
    this.props.close(false);
  };

  handleFormList = (item) => {
    const { formList } = this.state;
    if (/stepVOs\d+/.test(item)) {
      return {
        component: InputNumber,
        name: formList[item].name,
        required: true,
        params: {
          className: 'new-unit__input',
        }
      };
    } else {
      return formData[item];
    }
  };

  renderForm = () => {
    const { formList } = this.state;
    const { form: { getFieldDecorator }, user: { userOID }, params: { levelCode, levelOrgId, levelOrgName, readOnly }, company: { setOfBooksId } } = this.props;
    const formItemLayout = { labelCol: { span: 8 }, wrapperCol: { span: 10, offset: 0 } };
    const formArray = Object.keys(formList)
      .map(item => {
        const middleForm = this.handleFormList(item);
        const { name, child, params = {}, required, component, extra } = middleForm;
        params.disabled = this.isReadOnly() || readOnly;
        if (item === 'currency') {
          params.params.userOId = userOID;
          params.params.setOfBooksId = levelCode === 'COMPANY' ? setOfBooksId : levelOrgId;
          params.params.companyId = levelCode === 'COMPANY' ? levelOrgId : null;
        }else if (item === 'userGroupVOs') {
          params.priority = {levelCode, levelOrgId};
        }
        return (
          <Form.Item  extra={extra} label={name}>
            {
              getFieldDecorator(item, {
                rules: [{
                  required: !!required,
                  message: messages('expense-12.key152',{arg1: name})/*请选择{arg1}*/
                }],
                initialValue: formList[item].initData,
                valuePropName: formList[item].valuePropName || 'value'
              })(React.createElement(component, params, child))
            }
          </Form.Item>
        );
      });

    formArray.splice(1, 0, (
      <Priority
        top={'SET_OF_BOOK'}
        single={false}
        disabled={true}
        onChange={this.handlePriority}
        showCompany
        companyProps={{
          single: true,
          disabled: true
        }}
        defaultValue={{
          levelCode,
          levelOrgId,
          levelOrgName
        }}
        formItemLayout={formItemLayout}
        required
      />
    )); // 权限套装直接插入Item list
    return formArray;
  };


  render() {
    const { submitLoading } = this.state;
    const { params: { readOnly } } = this.props;
    return (
      <section className='new-unit new-form'>
        <Form onSubmit={this.handleSubmit}>
          {
            this.renderForm()
          }
          <div className="slide-footer">
            <Button
              type="primary"
              disabled={this.isReadOnly() || readOnly}
              htmlType="submit"
              loading={submitLoading}>
              {messages('common.save')/*保存*/}
            </Button>
            <Button
              onClick={this.handleCancel}
              disabled={this.isReadOnly() || readOnly}
              className="new-unit-cancel">
              {messages('common.cancel')/*取消*/}
            </Button>
          </div>
        </Form>
      </section>
    );
  }
}


function mapStateToProps(state) {
  return {
    currentMenuPermission: state.main.currentMenuPermission,
    user: state.login.user,
    company: state.login.company
  };
}

const WrappedNewUnit = Form.create()(NewLadderModeRule);

export default WrappedNewUnit;
